import React, { memo, Component } from 'react'
import {
    getChatConnection,
    sendMessage,
    getChatHistory,
    getNewMessageCount,
    clearNewMessageCount,
    searchUser,
    addConnection,
    closeConnection
} from '@/api/user'
import { baseUrl } from '../../assets/baseUrl'
import { Input, Button, message, Badge, Select,notification } from 'antd';
import { StudentInfo } from '../../utils/model';
import './index.css'
import $ from 'jquery'
import { withRouter } from "react-router-dom";
const { TextArea } = Input;
const BaseUrl = baseUrl()
const { Option } = Select;
class chatIndex extends Component {
    static contextType = StudentInfo
    constructor(props) {
        super(props);
        this.state = {
            studentId: null,
            closeIcon: false,  //关闭弹框按钮
            hoverWhich: null, //鼠标放在哪一个对话者上
            chooseWhich: 0, //选择聊天对象
            sendingContent: '', //文本域内容
            connectionList: [], //聊天连接对象列表
            hisStudentId: null, //聊天对象的id
            hisHeadPicUrl: null, //聊天对象头像url
            hisNickName: null, //聊天对象昵称
            hisUserType: null, //聊天对象类型
            chatHistory: [], //聊天历史记录
            newMessageCount: null, //获取未读消息数量
            noRepeatHistory: 0, //轮询避免重复获取历史记录    为0打开页面会获取历史聊天记录，为1则不会获取历史记录
            myHeadPicUrl: null,
            searchUserList: [],   //搜索出来的用户列表
        }
    }
    componentDidMount() {
        this.setState({
            myHeadPicUrl: this.context?.studentInfo?.headPicUrl,
            studentId: this.context?.studentInfo?.studentId
        },()=>{
            setInterval(() => {
                if (!localStorage.getItem('closeIcon') == "false") {
                    this.openChatModal()
                    localStorage.setItem('closeIcon', false)
                }
            }, 200)
            this.getConnection()
            window.getcount = setInterval(() => {
                this.getMessageCount()
            }, 5000)
        })
    }

    //获取聊天对象列表
    getConnection() {
        getChatConnection().then(res => {
            this.setState({
                connectionList: res.data.data,
            }, () => {
                let { connectionList } = this.state
                if (connectionList.length > 0)
                    this.setState({
                        hisStudentId: connectionList[0].hisStudentId,
                        hisHeadPicUrl: connectionList[0].hisHeadPicUrl,
                        hisNickName: connectionList[0].hisNickName,
                        hisUserType: connectionList[0].hisUserType
                    })
            })
        })
    }

    getMessageCount = () => {   //获取未读消息数量
        getNewMessageCount().then(res => {
            if (res.data?.code === 201) {
                clearInterval(window.getcount)
                this.props.history.push("/login");
            }
            if (res.data?.newMessage){
                this.props.setnewMessageCount(res.data?.newMessage.length)
                localStorage.setItem('emailCount',res.data?.newMessage.length)
                res.data?.newMessage.map((item)=>{
                    notification.open({
                        message: item.title,
                        description: item.content,
                        onClick: () => {
                            console.log('点击!');
                        },
                    });
                })
            }
            this.setState({
                newMessageCount: res.data?.newChatCount
            })
        })
    }

    openChatModal = () => {   //点击图标打开聊天弹框
        clearInterval(window.getcount)
        this.getConnection()
        //把未读消息数清0
        let { connectionList } = this.state
        if (connectionList.length > 0) {
            clearNewMessageCount()
        }
        this.setState({
            newMessageCount: 0,
            closeIcon: true
        }, () => {
            setTimeout(() => {
                $("#messageArea").animate({ scrollTop: this.getAllHeight() }, 500);
            }, 1000)
        })
        if (connectionList.length > 0) {
            window.timer = setInterval(() => {   //弹框打开才请求聊天记录
                this.getHistory()
            }, 5000)
        }
    }

    getHistory = () => {    //获取聊天记录
        let data = { hisId: this.state.hisStudentId, repeat: this.state.noRepeatHistory }
        getChatHistory(data).then(res => {
            let { chatHistory, noRepeatHistory } = this.state
            if (noRepeatHistory === 0)
                this.setState({
                    chatHistory: [...res.data?.data],
                    noRepeatHistory: 1
                })
            else if (noRepeatHistory === 1 && res.data?.data.length > 0)
                this.setState({
                    chatHistory: [...chatHistory, ...res.data?.data],
                }, () => {
                    if (res.data?.data.length > 0)
                        setTimeout(() => {
                            $("#messageArea").animate({ scrollTop: this.getAllHeight() }, 500);
                        }, 200)
                })
        })
    }
    getAllHeight = () => {    //获取滚动区高度 
        let totalHeight = 0;
        $("#messageArea").children().each(function () {
            totalHeight = totalHeight + $(this).outerHeight(true);
        });
        return totalHeight + 2000   //结果不准，原因未知，加个两千保底
    }
    sendMessage = () => {   //发送消息
        let { hisStudentId, hisHeadPicUrl, sendingContent, hisNickName, hisUserType, chatHistory } = this.state
        if (!this.state.hisStudentId) {
            message.warning('请先选择聊天对象！')
            return
        }
        else if (this.state.sendingContent.length > 255) {
            message.warning('内容过长!')
            return
        }
        this.setState({
            sendingContent: ''
        })
        let data = {
            hisId: parseInt(hisStudentId),
            content: sendingContent,
            createTime: Date.parse(new Date())
        }
        sendMessage(data).then()
        data.hasRead = 0
        data.senderId = this.state.studentId
        data.myStudentId = this.state.studentId
        this.setState({
            chatHistory: [...chatHistory, data]
        }, () => {
            $("#messageArea").animate({ scrollTop: this.getAllHeight() }, 1000);
        })
    }
    chooseChat = (item, index) => {
        this.setState({
            chooseWhich: index,
            hisStudentId: item.hisStudentId,
            hisHeadPicUrl: item.hisHeadPicUrl,
            hisNickName: item.hisNickName,
            hisUserType: item.hisUserType,
            noRepeatHistory: 0,
            chatHistory: []
        }, this.getHistory.bind(this))
        setTimeout(()=>{
            $("#messageArea").animate({ scrollTop: this.getAllHeight() }, 1000);
        }, 500)
    }

    closeModal = () => {  //关闭弹框
        clearInterval(window.timer)   //清除获取聊天记录的轮询
        this.setState({
            chooseWhich: null,
            chatHistory: [],
        })
        clearNewMessageCount()  //清除未读消息数，代表聊天框打开期间未读消息数不会增长
        localStorage.setItem('closeIcon', false)
        this.setState({ closeIcon: false, newMessageCount: null }, () => {
            window.getcount = setInterval(() => {
                this.getMessageCount()
            }, 5000)
        })
    }

    //搜索用户
    search = (value) => {
        if (value.length <= 2)   //起码输入三位才查询
            return
        else {
            searchUser({ keyword: value }).then((res) => {
                this.setState({
                    searchUserList: res.data.results
                })
            })
        }
    }

    //添加聊天对象 
    addConnecter(hisStudentId) {
        addConnection({
            hisStudentId: hisStudentId,
            noRepeatHistory: 0
        }).then(() => {
            // this.getHistory()
            this.getConnection()
        }
        )
    }

    //删除聊天对象
    closeConnecter(hisStudentId, index) {
        closeConnection({
            hisStudentId: hisStudentId
        }).then(() => {
            this.getConnection()
            this.setState({
                chatHistory: [],
                chooseWhich: null
            })
        }
        )
    }
    render() {
        // const {userInfo} = this.state
        const { closeIcon, hoverWhich, sendingContent, connectionList, chooseWhich, chatHistory, newMessageCount, searchUserList } = this.state
        return (
            <div>
                <div style={{
                    position: 'fixed',
                    left: 20,
                    bottom: 30,
                    zIndex: 99
                }}>
                    <Badge count={newMessageCount}>
                        <img src={BaseUrl + 'chat.png'} alt="" style={{   //左下角图标
                            width: 64,
                            height: 64,
                            border: 'none',
                            zIndex: 99999,
                            cursor: 'pointer'
                        }} onClick={this.openChatModal.bind(this)} />
                    </Badge>
                </div>
                {   //聊天框
                    closeIcon && <div className={closeIcon ? 'openmodal' : 'closemodal'}>
                        <div>
                            <div className='ID-search'>
                                <Select
                                    showSearch
                                    style={{
                                        width: '13vw',
                                        marginBottom: '1vh'
                                    }}
                                    placeholder="输入至少3位UID搜索用户"
                                    notFoundContent={<div>未找到匹配用户</div>}
                                    optionFilterProp="children"
                                    optionLabelProp="null"
                                    onSearch={e => this.search(e)}
                                    // onFocus={onFocus}
                                    // onBlur={onBlur}
                                    // onSearch={onSearch}
                                    filterOption={(input, option) =>
                                        option.props.key.toString().indexOf(input.toString()) >= 0 &&
                                        this.state.connectionList.filter((item) => item.hisStudentId == option.props.key).length == 0  //要求不在已有联系人列表内
                                    }
                                >
                                    {
                                        searchUserList.map((item, index) => {
                                            return (
                                                <Option key={item.studentId} value={item.nickName}>
                                                    <div className='flex' style={{ fontSize: 10 }} onClick={this.addConnecter.bind(this, item.studentId)}>
                                                        <img src={BaseUrl + item.headPicUrl} alt="" style={{
                                                            width: 24,
                                                            height: 24,
                                                            borderRadius: '50%',
                                                            marginRight: 3
                                                        }}
                                                        />
                                                        {item.nickName}
                                                    </div>
                                                </Option>
                                            )
                                        })
                                    }
                                </Select>
                            </div>
                            <div style={{                                        //左侧选择列表
                                height: '48vh',
                                width: '13vw',
                                background: 'rgba(255,255,255,.5)',
                                borderRadius: '16px 0 0 16px',
                                overflowY: 'auto',
                            }}>
                                <img src={BaseUrl + 'close.png'} alt="" style={{    //聊天框叉叉
                                    height: 24,
                                    width: 24,
                                    borderRadius: "50%",
                                    position: 'absolute',
                                    right: 20,
                                    top: 20,
                                    border: 'none',
                                    cursor: 'pointer'
                                }} onClick={this.closeModal.bind(this)}
                                />
                                {
                                    connectionList.map((item, index) => {
                                        return (
                                            <div className={
                                                index === chooseWhich ? 'flex chooseChat choose' : 'flex chooseChat'
                                            }
                                                style={{ padding: '6px 0 6px 4px' }}
                                                onMouseOver={() => { this.setState({ hoverWhich: index }) }}
                                                onMouseLeave={() => { this.setState({ hoverWhich: null }) }}
                                                onClick={this.chooseChat.bind(this, item, index)}
                                                key={index}
                                            >

                                                <div style={{ position: 'relative' }}>
                                                    <img src={BaseUrl + item.hisHeadPicUrl} alt="" style={{
                                                        height: 48,
                                                        width: 48,
                                                        borderRadius: "50%"
                                                    }} />
                                                    <div style={{
                                                        position: 'absolute',
                                                        bottom: -5,
                                                        right: 0
                                                    }}>
                                                        {
                                                            item.hisUserType === 1 && <i className="iconfont icon-huiyuanvip"   //用户类型为1 ，用vip图标
                                                                style={{
                                                                    color: 'red',
                                                                    border: '1px solid white',
                                                                    borderRadius: '50%'
                                                                }}
                                                            ></i>
                                                        }
                                                        {
                                                            item.hisUserType === 2 && <i className="iconfont icon-SVIP-fill"   //用户类型为2 ，用svip图标
                                                                style={{
                                                                    color: 'yellow',
                                                                }}
                                                            ></i>
                                                        }
                                                        {
                                                            item.hisUserType === 99 && <i className="iconfont icon-renzheng"   //用户类型为99 ，用官方开发图标
                                                                style={{
                                                                    color: 'green',
                                                                }}
                                                            ></i>
                                                        }
                                                    </div>
                                                </div>
                                                <div style={{ width: 30, margin: '12px 0 0 8px', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} className={
                                                    item?.hisUserType === 1 ? 'font-semibold text-red-500' :
                                                        item?.hisUserType === 2 ? 'font-semibold text-yellow-300' :
                                                            item?.hisUserType === 99 ? 'font-semibold text-green-600' :
                                                                'font-semibold'
                                                }>
                                                    {item.hisNickName}
                                                    {
                                                        index === hoverWhich && <img src={BaseUrl + 'close.png'} alt="" style={{   //关闭与该用户的对话
                                                            width: 18,
                                                            height: 18,
                                                            border: 'none',
                                                            zIndex: 99999,
                                                            cursor: 'pointer',
                                                            marginLeft: '45px',
                                                            position: 'absolute',
                                                            right: 5, top: 20
                                                        }} onClick={this.closeConnecter.bind(this, item.hisStudentId, index)} />
                                                    }
                                                </div>
                                            </div>
                                        )
                                    })
                                }
                            </div>
                        </div>
                        <div>
                            <div id='messageArea' style={{
                                height: '32vh',
                                width: '36vw',
                                margin: '10px 0 0 30px',
                                borderRadius: '16px',
                                border: '1px solid yellow',
                                background: 'rgba(255,255,255,.6)',
                                overflowY: 'auto',
                                padding: '5px 10px'
                            }}>
                                {
                                    chatHistory?.map((item) => {
                                        return (
                                            <div>
                                                {
                                                    item.senderId === item.hisStudentId ? <div className='flex messageBox'>
                                                        <img src={BaseUrl + this.state.hisHeadPicUrl} alt="" className='message-icon' />
                                                        {/* <div>{item.hisNickName+'   '+this.formatDate(item.createTime)}</div> */}
                                                        <div className='contentBoxhe'>{item.content}</div>
                                                    </div> : <div style={{ position: 'relative' }}>
                                                        <div className='flex messageBox messBoxRight'>
                                                            {/* <div>{'我  '+this.formatDate(item.createTime)}</div> */}
                                                            <div className='contentBoxme'>{item.content}</div>
                                                            <img src={BaseUrl + this.state.myHeadPicUrl} alt="" className='message-icon' />
                                                        </div>
                                                        <div className='flex messageBox' style={{ opacity: 0 }}>
                                                            <div className='contentBoxme'>{item.content}</div>
                                                            <img src={BaseUrl + this.state.myHeadPicUrl} alt="" className='message-icon' />
                                                        </div>
                                                    </div>
                                                }
                                            </div>
                                        )
                                    })
                                }
                                {/* 信息对话框 */}
                                {/* <div id='bot' style={{height:30}}></div> */}
                            </div>
                            <div style={{
                                height: '18vh',
                                width: '36vw',
                                margin: '10px 0 0 30px',
                                borderRadius: '16px',
                                border: '1px solid yellow',
                                background: 'rgba(255,255,255,.6)',
                                zIndex: 999,
                                position: 'relative'
                            }}>
                                {/* 信息输入框 */}
                                <TextArea rows={4} suffix='123' value={sendingContent} style={{
                                    height: '18vh',
                                    minHeight: '18vh',
                                    maxHeight: '18vh',
                                    width: '36vw',
                                    borderRadius: '16px',
                                    zIndex: 998,
                                    paddingBottom: 30,
                                    background: 'rgba(255,255,255,.6)',
                                }} onChange={e => this.setState({ sendingContent: e.target.value })} />
                                <Button className='buttonSend' onClick={this.sendMessage.bind(this)}>发送</Button>
                                <div className={sendingContent.length > 255 ? 'font-warning' : ''} style={{
                                    position: 'absolute',
                                    bottom: 5,
                                    left: 10,
                                    zIndex: 999,
                                }}>{sendingContent.length}/255</div>
                            </div>
                        </div>
                    </div>
                }
            </div>
        )
    }
}
export default withRouter(chatIndex)
